﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;

namespace SharpMedia.Input
{
    /// <summary>
    /// Hides a mouse cursor when it is not moved within a form for a while.
    /// </summary>
    public class MouseHider : IDisposable
    {
        private Form form;
        private TripTrigger mouseTrigger = new TripTrigger(new TimeSpan(0, 0, 1));
        private Point cursorPosition;
        private bool disposed = false;

        public event MouseEventHandler MouseMoved;

        public bool CursorHidden { get; private set; }

        public MouseHider(Form form)
        {
            this.form = form;
            // Hide Mouse
            // Note: The Cursor.hide and show must be balanced. 
            form.MouseMove += MouseMove;
            CursorHidden = true;
            mouseTrigger.TimeOut += new EventHandler(delegate { Cursor.Hide(); CursorHidden = true; });
            mouseTrigger.FirstTrigger += new EventHandler(delegate { Cursor.Show(); CursorHidden = false; });
            Cursor.Hide();
            form.MouseClick += new MouseEventHandler(form_MouseClick);
            form.MouseDown += new MouseEventHandler(form_MouseDown);
            form.MouseUp += new MouseEventHandler(form_MouseUp);
        }

        void form_MouseUp(object sender, MouseEventArgs e)
        {
            mouseTrigger.Trigger();
        }

        void form_MouseDown(object sender, MouseEventArgs e)
        {
            mouseTrigger.Trigger();
        }

        void form_MouseClick(object sender, MouseEventArgs e)
        {
            mouseTrigger.Trigger();
        }

        

        public void Dispose()
        {
            form.MouseMove -= MouseMove;
            mouseTrigger.Stop(true);
            disposed = true;
        }

        private void MouseMove(object o, MouseEventArgs me)
        {

            if (me.Location != cursorPosition)
            {
                mouseTrigger.Trigger();
                cursorPosition = me.Location;
                if (MouseMoved != null)
                {
                    MouseMoved(this, me);
                }
            }
            cursorPosition = me.Location;
        }

        public void Update(TimeSpan ts)
        {
            if (disposed)
                return;

            

            Point p = form.PointToClient(Cursor.Position);
            mouseTrigger.Update(ts);
            if (p != cursorPosition)
            {
                p = cursorPosition;
            }


        }
    }
}
